package com.atguigu.ssyx.acl.service.serviceimpl;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.acl.utils.PermissionHelper;
import com.atguigu.ssyx.model.acl.Permission;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    //递归删除菜单
    @Override
    public boolean removeChildById(Long id) {
        List<Long> idList = new ArrayList<>();
        this.selectChildListById(id,idList);
        idList.add(id);
        baseMapper.deleteBatchIds(idList);
        return true;
    }

    /**
     *	递归获取子节点
     * @param id
     * @param idList
     */
    private void selectChildListById(Long id, List<Long> idList){
        List<Permission> childList = new ArrayList<>();
        childList = baseMapper.selectList(new QueryWrapper<Permission>().eq("pid",id).select("id"));
        childList.stream().forEach(item-> {
            idList.add(item.getId());
            selectChildListById(item.getId(),idList);
        });
    }



    //获取菜单列表
    @Override
    public List<Permission> queryAllMenu() {
        //获取全部权限数据
        List<Permission> allPermissionList = baseMapper.selectList
                (new QueryWrapper<Permission>().orderByAsc("CAST(id AS SIGNED)"));

        //把权限数据建成树形权限结构
        List<Permission> result = PermissionHelper.build(allPermissionList);

        return result;
    }


}
